<?php

namespace app\controllers\h5\mini;

use app\controllers\h5\base\H5Controller;
use app\controllers\h5\mini\en\WXBizDataCrypt;
use app\models\system\SetApp;
use app\models\system\SetBasic;
use app\models\system\SetWx;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserPayPassword;
use app\redis\user\UserCache;
use app\services\User as Service;
use app\util\Debug;
use app\util\Request;
use app\util\JWT;
use app\util\Util;

class UserController extends H5Controller
{
    public function actionAgreement()
    {
        $model = SetBasic::getLastOne();

        return $this->successEncode(['text' => $model->agreement]);
    }

    // get app set
    public function actionGetSet() {
        $app = SetApp::getLastOne()->toArray();

        return $this->successEncode(['app' => $app]);
    }

    public function actionLogin()
    {
        $code = $this->post('code');
        $referrer = $this->post('referrer', 0);

        $set = SetWx::getLastOne(false);
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$set->app_id}&secret={$set->app_secret}&js_code={$code}&grant_type=authorization_code";

        try {
            $result = Request::get($url);

            $response = json_decode($result, true);

            // 调试的时候用
            // if (isset($response['errcode']) && $response['errcode'] != 0) {
            //     return $this->fail('后台设置app_secret');
            // }

            // var_dump($response);exit;

            if ($response['openid'] && $response['session_key']) {

                $user = User::findOne(['openid' => $response['openid']]);

                // var_dump($user);exit;

                if (!$user) {

                    // register
                    $user = new User();
                    if ($referrer > 0) {

                        // if (Service::checkReferrer($user->id, $referrer)) {
                        //     return $this->fail('推荐人错误!!!');
                        // }

                        $user->referrer_id = $referrer;
                    }
                }

                $user->openid = $response['openid'];
                $user->session_key = $response['session_key'];

                $user->login_ip = Util::getClientIp();

                // 排号
                $user->sort = 9999;

                if (!$user->save()) {
                    // var_dump($user->getFirstErrors());exit;
                    throw new \Exception('user error');
                }

                // var_dump(11111);exit;

                // account
                $account = UserAccount::findOne(['user_id' => $user->id]);
                if (!$account) {
                    $account = new UserAccount();
                    $account->user_id = $user->id;
                    $account->save();
                }

                $token = JWT::createToken(
                    [
                        'openid' => $user->openid,
                        'session_key' => $user->session_key,
                        'id' => $user->id,
                    ],
                    \Yii::$app->params['JWT_H5_KEY'],
                    \Yii::$app->params['JWT_H5_EXPIRED']
                );

                // 保存到redis
                // UserCache::createOne($user->id, $user->referrer_id, $user->level);

                return $this->successEncode([
                    'token' => $token,
                    'nickname' => $user->nickname,
                    'mobile' => $user->mobile,
                    'session_key' => $user->session_key
                ]);
            }
        } catch (\Exception $e) {
            // mobile不能添加为索引
            var_dump($e->getMessage());exit;
            Debug::wx('login', $e->getMessage());
        }
    }

    public function actionSaveInfo()
    {
        $avatar = $this->post('avatar');
        $nickname = $this->post('nickname');
        $sex = $this->post('sex');

        // 也可以在这里转成base64图片
        // $str = file_get_contents($avatar);
        // $base64 = chunk_split(base64_encode($str));
        // $avatar = "data:image/jpg/png/gif;base64,' . $base64 .'";

        // var_dump($this->user->id);exit;

        $model = User::findOne(['id' => $this->user->id]);
        if ($model) {

            $model->nickname = base64_encode($nickname);
            $model->sex = $sex;
            $model->avatar = $avatar;

            if ($model->save()) {
                return $this->success();
            } else {
                // var_dump($model->getErrors());
            }
        } else {
            // 如果没有电话号码, 需要退回到电话获取地方
            return $this->fail('重新获取电话', -100);
        }

        return $this->fail('获取失败');
    }

    public function actionSaveMobile()
    {
        $iv = $this->post('iv');
        $data = $this->post('data');
        $session_key = $this->post('session_key');

        // var_dump($iv, $data, $session_key);exit;

        $set = SetWx::getLastOne(false);

        $pc = new WXBizDataCrypt($set->app_id, $session_key);
        $errCode = $pc->decryptData($data, $iv, $result);

        // 如果拒绝了
        if (!$result) {
            $user = User::findOne(['id' => $this->user->id]);
            if ($user) {
                $user->delete();
            }
            return $this->fail('获取手机失败, 请重试', -100);
        }

        if ($errCode == 0 && $result) {
            $user = User::findOne(['id' => $this->user->id]);
            if ($user) {
                // import user data ....
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    $result = json_decode($result, true);
                    $user->mobile = $result['phoneNumber'];
                    $user->save();


                    // 重新创建token(可能ID变了)
                    $token = JWT::createToken(
                        [
                            'openid' => $user->openid,
                            'session_key' => $user->session_key,
                            'id' => $user->id,
                        ],
                        \Yii::$app->params['JWT_H5_KEY'],
                        \Yii::$app->params['JWT_H5_EXPIRED']
                    );

                    $transaction->commit();
                    return $this->successEncode([
                        'result' => true,
                        'token' => $token,
                        'id' => $user->id
                    ]);
                } catch (\Exception $e) {
                    $transaction->rollBack();
                    // var_dump($e->getMessage());exit;
                    return $this->fail($e->getMessage());
                }
            }
        }

        return $this->fail('获取失败mobile');
    }

    public function actionGetOpenid()
    {
        $openid = User::find()
            ->where(['id' => $this->user->id])
            ->select(['openid'])
            ->scalar();

        if ($openid) {
            return $this->successEncode([
                'openid' => $openid
            ]);
        }

        return $this->fail('获取用户信息失败,请退出重新登录');
    }

    // 修改图像
    public function actionChangeAvatar()
    {
        $nickname = $this->post('nickname');
        $avatarUrl = $this->post('avatarUrl');
        $base64Image = $this->post('base64Image');

        // var_dump($avatarUrl);exit;

        // $url = 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132';
        // if (!$avatarUrl || $url == $avatarUrl) {
        //     return $this->fail('请修改用户头像');
        // }
        //
        // if (!$nickname || $nickname == '微信用户') {
        //     return $this->fail('请修改用户昵称');
        // }

        if (!$avatarUrl) {
            return $this->fail('请修改用户头像');
        }

        if (!$nickname) {
            return $this->fail('请修改用户昵称');
        }


        if ($nickname) {
            $nickname = base64_encode($nickname);
        }


        $model = User::findOne(['id' => $this->user->id]);
        if (!$model) {
            return $this->fail('请登录登录', -100);
        }

        $model->base64Image = $base64Image;
        $model->nickname = $nickname;
        $model->avatar = $avatarUrl;
        $model->save();

        return $this->success();
    }

    // 检测是否设置支付密码
    public function actionCheckSetPassword()
    {
        $model = UserPayPassword::findOne(['user_id' => $this->user->id]);

        return $this->successEncode(['result' => boolval($model)]);
    }
}